#/bin/sh

WORKDIR=$HOME/build-squash
mkdir -p $WORKDIR/{rootfs,mnt,initrd,output}
cd $WORKDIR


# 1、制作迷你根文件系统
sudo debootstrap --variant=minbase jammy rootfs http://archive.ubuntu.com/ubuntu

# 装必要软件
sudo chroot rootfs /bin/bash <<'CHROOT'
apt update
apt install -y --no-install-recommends \
  xfce4 xfce4-goodies tigervnc-standalone-server lightdm \
  openssh-client firefox-esr curl ca-certificates
# 创建 vnc 用户
useradd -m -s /bin/bash vnc
echo "vnc:123456" | chpasswd
CHROOT


# 2、VNC 自启 + 全屏脚本


# 系统级 systemd 服务
sudo tee rootfs/etc/systemd/system/vnc-auto.service <<'EOF'
[Unit]
Description=Auto VNC at boot
After=network.target

[Service]
Type=simple
User=vnc
ExecStart=/usr/local/bin/vnc-auto.sh
Restart=always

[Install]
WantedBy=multi-user.target
EOF

sudo tee rootfs/usr/local/bin/vnc-auto.sh <<'EOF'
#!/bin/bash
export DISPLAY=:1
vncserver :1 -geometry 1920x1080 -depth 24 -localhost no
# 自动连远端云桌面（示例：192.168.50.10:5901）
sleep 3
exec vncviewer -FullScreen -PreferredEncoding tight 192.168.194.20:5901
EOF
sudo chmod +x rootfs/usr/local/bin/vnc-auto.sh
sudo chroot rootfs systemctl enable vnc-auto.service lightdm


# 3、 打包 squashfs

sudo mksquashfs rootfs output/live.squashfs \
  -comp zstd -b 256K -Xcompression-level 19 \
  -e rootfs/proc rootfs/sys rootfs/dev rootfs/run

# 4、制作 initrd（最小内存盘）

mkdir initrd/{bin,dev,proc,sys,newroot}
cat > initrd/init <<'EOF'
#!/bin/busybox sh
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev

# 网络 + DHCP
ip link set eth0 up
udhcpc -i eth0 -s /etc/udhcpc.script

# 拉 squashfs
mount -t nfs $NFS_SERVER:/tftpboot /mnt
mount -t squashfs -o loop /mnt/live.squashfs /newroot

# 可写 overlay（可选）
mkdir /tmp/ovl /tmp/work
mount -t overlay overlay \
  -o lowerdir=/newroot,upperdir=/tmp/ovl,workdir=/tmp/work /newroot

exec switch_root /newroot /sbin/init
EOF
chmod +x initrd/init

# 打包
cd initrd
find . | cpio -H newc -o | gzip > ../output/initrd.gz
cd ..
